import { c2s, jumpTo, getAppData, sessionStorage } from '@/deps/utils'
import { Message } from 'element-ui';
import { isArray, isNaN } from 'lodash'
import { bus } from '+/deps/env'
const http = (url, data, method, responseType, config) => {
  if (method === 'get' || method === 'GET') {
    if (!!data) {
      url = url + '?' + parseParams(data)
    }
  }
  return new Promise(function (resolve, reject) {
    c2s(
      {
        url: url,
        data: data,
        method: method,
        responseType: responseType || 'json',
        onSuccess: res => {
          resolve(res)
        },
        onError(e) {
          if ([40405, 400, '400'].includes(e.code)) {
            Message({
              message: '登录失效，请重新登录！',
              type: 'error'
            })
            jumpTo('login')
          }
          reject(e)
        }
      },
      Object.assign({ ajaxType: 'none' }, { ...config, mask: false })
    )
  })
}
export function httpFun({ url, data, methods, responseType, config }) {
  return new Promise(function (resolve, reject) {
    http(url, data, methods, responseType, config).then(
      res => {
        resolve(res)
      },
      rej => {
        reject(rej)
      }
    )
  })
}
const resetForm = form => {
  !!form ? form.resetFields() : null
}
const download = (data, name) => {
  if (!data) {
    return
  }
  let url = data
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', name || 'excel.xlsx')
  document.body.appendChild(link)
  link.click()
}
const priview = url => {
  if (!url) {
    return
  }
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('target', '_blanck')
  document.body.appendChild(link)
  link.click()
}
const removeZero = str => {
  return str.replace(/\b(0+)/gi, '')
}

export const parseParams = function (data) {
  try {
    let tempArr = []
    for (let i in data) {
      let key = encodeURIComponent(i)
      let value = encodeURIComponent(data[i])
      tempArr.push(key + '=' + value)
    }
    let urlParamsStr = tempArr.join('&')
    return urlParamsStr
  } catch (err) {
    return ''
  }
}

const toFix = (num, len) => {
  return isNaN(Number(num)) || !isFinite(Number(num))
    ? Number(0).toFixed(len)
    : Number(num).toFixed(len)
}
const formatDateToSql = function (data) {
  if (!data) {
    return ''
  }
  var d = new Date(data)
  var year = d.getFullYear()
  var month = d.getMonth() + 1
  var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate()
  var hour = d.getHours()
  var minutes = d.getMinutes()
  var seconds = d.getSeconds()
  return (
    year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
  )
}
const formatDate = (fmt, date) => {
  if (!date) {
    return ''
  }
  date = new Date(date)
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}
const getToday = () => {
  return [
    formatDate('yyyy-MM-dd', new Date()),
    formatDate('yyyy-MM-dd', new Date())
  ]
}
const getMonth = () => {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = new Date(year, month, 0)
  return [
    year + '-' + (month < 10 ? '0' + month : month) + '-' + '01',
    year + '-' + (month < 10 ? '0' + month : month) + '-' + day.getDate()
  ]
}
const statistics = (category, action, optLabel, optValue) => {
  var _hmt = window._hmt || []
  if (window.location.host === 'i.yazuo.com') {
    _hmt.push([
      '_trackEvent',
      category,
      action,
      `${getAppData('rootDomain').name}-${getAppData('currentDomain').name}`,
      optValue
    ])
  }
  window._hmt = _hmt
}
const getCookie = cookieName => {
  var cookie = document.cookie
  var i = cookie.indexOf(cookieName)
  if (i === -1) {
    return null
  } else {
    var starti = i + cookieName.length + 1
    var endi = cookie.indexOf(';', starti)
    if (endi === -1) {
      return cookie.slice(starti)
    } else {
      return cookie.slice(starti, endi)
    }
  }
}
const getDay = day => {
  var today = new Date()
  var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day
  today.setTime(targetday)
  var tYear = today.getFullYear()
  var tMonth = today.getMonth()
  var tDate = today.getDate()
  tMonth = doHandleMonth(tMonth + 1)
  tDate = doHandleMonth(tDate)
  return tYear + '-' + tMonth + '-' + tDate
}
const doHandleMonth = month => {
  var m = month
  if (month.toString().length === 1) {
    m = '0' + month
  }
  return m
}
const validateNumber = (value, callback, mes) => {
  if (!value) {
    callback(new Error(mes))
    return
  }
  if (parseInt(value) > 0) {
    callback()
  } else {
    callback(new Error('必须是大于0的数字'))
  }
}
const validateNum = (value, callback, mes) => {
  const reg = new RegExp('^[-+]?[0-9]*\.?[0-9]+$')
  if (value === '') {
    callback(new Error(mes))
    return
  }
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('必须是数字'))
  }
}

const validateArray = (value, callback, mes) => {
  if (isArray(value) && value.length > 0) {
    callback()
  } else {
    callback(new Error(mes))
  }
}
const validateMax100 = (value, callback, mes) => {
  if (!value) {
    callback(new Error(mes))
    return
  }
  if (parseInt(value) > 0 && parseInt(value) <= 100) {
    callback()
  } else {
    callback(new Error('必须是大于0小于等于100的数字'))
  }
}
const renderButton = ({ rObj, row, clickFun, label, props }) => {
  return rObj(
    'el-button',
    {
      props,
      attrs: {
        type: 'text'
      },
      on: {
        click: clickFun
      }
    },
    label
  )
}
const clearArrByKey = ({ keys, data }) => {
  keys.forEach(key => {
    data[key] = []
  })
}
const clearStrByKey = ({ keys, data }) => {
  keys.forEach(key => {
    data[key] = ''
  })
}
const downloadBlob = (data, name) => {
  if (!data) {
    return
  }
  let url = window.URL.createObjectURL(new Blob([data]))
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', name)
  document.body.appendChild(link)
  link.click()
}
const messageConfirm = (vm, data = {titleText: '确认要删除吗？', title: '提示', confirm: '确定', message: '', type: 'warning'}) => {
  return new Promise((resolve) => {
    vm.$confirm(data.titleText, data.title, {
      confirmButtonText: data.confirm,
      cancelButtonText: '取消',
      message: data.message,
      type: data.type
    }).then(() => resolve(true)).catch(() => resolve(false))
  });
};
export const utils = {
  http,
  httpFun,
  download,
  priview,
  resetForm,
  toFix,
  formatDateToSql,
  getMonth,
  getToday,
  jumpTo,
  formatDate,
  statistics,
  getCookie,
  removeZero,
  getDay,
  sessionStorage,
  validateNumber,
  validateNum,
  validateMax100,
  validateArray,
  renderButton,
  clearArrByKey,
  clearStrByKey,
  downloadBlob,
  bus,
  messageConfirm
};
